package com.yang.proxy.dynamicproxy.myjdk;

import java.io.*;

/**
 * @author yang
 * @version 0.1
 * @date 2019/4/16
 */
public class MyClassLoader extends ClassLoader {

    private File classPathFile;

    public MyClassLoader() {

        String path = MyClassLoader.class.getResource(" ").getPath();

        classPathFile = new File(path);
    }

    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {

        String className = MyClassLoader.class.getPackage().getName() + "." + name;

        if (null != className) {
            File classFile = new File(classPathFile, name.replaceAll("\\.", "/") + ".class");
            FileInputStream fis = null;
            ByteArrayOutputStream baos = null;

            try {
                fis = new FileInputStream(classFile);
                baos = new ByteArrayOutputStream();

                byte[] buff = new byte[1024];
                int length = 0;
                while ((length = fis.read(buff)) != -1) {
                    baos.write(buff, 0 , length);
                }

                return defineClass(className, baos.toByteArray(), 0, baos.size());
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return super.findClass(name);
    }
}
